<?php
include "includes/functions.php";
echo db_connect();
 
/// NOTE : THE FOLLOWING ARRAYS, AND REFERENCES TO THEM, AS WELL AS THE DB ACCESS ABOVE AND THE SELECT BELOW, \\
///        NEED TO BE ALTERED ACCORDING TO APPLICATION.

$artist_db = array();
$title_db = array();

	$input = strtolower( $_GET['input'] );
	$len = strlen($input);


$x=0;

if ($_GET['limit']) { $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0; $limit_clause = " LIMIT " . $limit; } else { $limit_clause = " LIMIT 20"; }

$query = 'SELECT artist, title, album_id FROM ml_albums WHERE `artist` LIKE "%' . $input . '%" OR `keywords` LIKE "%' . $input . '%" ' . $limit_clause;
$result = mysql_query ($query); //echo $query;
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
	$artist_db[$x] = $row[0];
	$title_db[$x] = $row[1];
	$id_db[$x] = $row[2];
	$x ++;
}

//print_r ($artist_db);


	
	$aResults = array();
	$count = 0;
	
	if ($len)
	{
		for ($i=0;$i<count($artist_db);$i++)
		{
		//echo "debug " . strtolower(substr($artist_db[$i],0,$len));
		
			//// COMMENTED OUT THE FOLLOWING IF - THIS MAY CAUSE THE RESULTING STRING TO BE TOO LONG, SEE ONCE KEYWORDS ARE IN. COULD MAKE 
			////  A SEPARATE BOX FOR A KEYWORK SEARCH IF SO, WOULD NEED TO REMOVE THE KEYWORD CLAUSE FROM THE ABOVE SELECT
			////
			//if (strtolower(substr($artist_db[$i],0,$len)) == $input)
			//{
				$count++;
				
				$aResults[] = array( "id"=>htmlspecialchars($id_db[$i]) ,"value"=>htmlspecialchars($artist_db[$i]), "info"=>htmlspecialchars($title_db[$i]) );
				//$aResults[] = array( "id"=>($i+1) ,"value"=>htmlspecialchars($artist_db[$i]), "info"=>htmlspecialchars($title_db[$i]) );
			//}
			
			if ($limit && $count==$limit)
				break;
		}
	}
	
if ($_GET['debug']) {
print_r ($artist_db); echo"<br><br>";
 echo $query. "<br><br>"; print_r($aResults); exit; 
 }

	//print_r ($aResults);
	
	header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
	header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header ("Pragma: no-cache"); // HTTP/1.0
	
	
	
	if (isset($_REQUEST['json']))
	{
		header("Content-Type: application/json");
	
		echo "{\"results\": [";
		$arr = array();
		for ($i=0;$i<count($aResults);$i++)
		{
			$arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\": \"\"}";
		}
		echo implode(", ", $arr);
		echo "]}";
	}
	else
	{
		header("Content-Type: text/xml");

		echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
		for ($i=0;$i<count($aResults);$i++)
		{
			echo "<rs id=\"".$aResults[$i]['id']."\" info=\"".$aResults[$i]['info']."\">".$aResults[$i]['value']."</rs>";
		}
		echo "</results>";
	}
?>